package org.wisdom.interceptor;

import java.util.Map;

import org.springframework.http.HttpHeaders;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.util.StringUtils;
import org.wisdom.context.WisdomContextHolder;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;

/**
 * feign拦截器,加载token，以便服务直接可以任意访问
 *
 * @author zhangzhiyan
 * @date 2021/07/21 13:12
 **/
@Slf4j
public class WisdomFeignInterceptor implements RequestInterceptor {

    private static final ThreadLocal<Map<String, Object>> TOKEN_THREAD_LOCAL = new ThreadLocal<>();

    private final String wisdomFeignSecretKey;

    private final String tokenSchema;

    public WisdomFeignInterceptor(String tokenSchema, String wisdomFeignSecretKey) {
        this.tokenSchema = tokenSchema;
        this.wisdomFeignSecretKey = wisdomFeignSecretKey;
    }

    public static void clearToken() {
        TOKEN_THREAD_LOCAL.remove();
    }

    /**
     * 添加token 当上下文中存在token时，代表此次请求有前端发起，则携带此token,当上下文中token为空时； 则表示此次请求由后端发起，则传输加密后的密钥
     *
     * @param template
     *            RequestTemplate
     * @author zhangzhiyan
     * @date 2021/07/21 13:38
     */
    @Override
    public void apply(RequestTemplate template) {
        // 获取token并加入到request参数中
        String token = WisdomContextHolder.getContext().getToken();
        log.debug("前端token令牌【{}】", token);
        if (!StringUtils.hasLength(token)) {
            PasswordEncoder passwordEncoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();
            String secretKey = passwordEncoder.encode(this.wisdomFeignSecretKey);
            template.header(HttpHeaders.AUTHORIZATION, "SK " + secretKey);
        }else {
            template.header(HttpHeaders.AUTHORIZATION, this.tokenSchema + token);
        }
    }
    public static void main(String[] args) {
        PasswordEncoder passwordEncoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();
        String secretKey = passwordEncoder.encode("S32^&sdfSdx231*23f!3#xWe");
        System.out.println(secretKey);
    }
}
